package versi.vitro.oaiserviceprovider.xml;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSInput;

import versi.vitro.oaiserviceprovider.helper.GeneralHelper;

public class ResourceResolverIntegrationTest {
    
    private Mockery context;

    @BeforeMethod
    public void setUp() {
	context = new Mockery();
    }
    
    @Test
    public void testResolveResourceWhenResourceIsRemote() {
   
        final String fileContentsStr = "some resource";
        final byte[] fileContentBytes = fileContentsStr.getBytes();
        
  	final GeneralHelper generalHelper = context.mock(GeneralHelper.class);
  	context.checking(new Expectations() {
  	    {
  	    }
  	});

  	ResourceResolver resourceResolver = new ResourceResolver(generalHelper)
  	{
  	    protected InputStream createInputStream(byte[] fileContents) {
  		return new ByteArrayInputStream(fileContentBytes);
  	    }

  	};
  	String type = "dont care";	
  	String namespaceURI = "also don't care";
  	String publicId = "used a bit";
  	// TODO RR add a sensible URL to the local properties file.
  	String systemId = "http://www.versi.edu.au";	// The only thing we care about. Assumes a local web server is running
  	String baseURI = "again don't care";
  	LSInput resource = resourceResolver.resolveResource(type, namespaceURI, publicId, systemId, baseURI);
  	
  	String result = resource.getStringData();
  	assert result.contains("Apache");
  	
  	context.assertIsSatisfied();
    }
    
    @Test
    public void testResolveResourceWhenResourceIsLocal() {
   
        final String fileContentsStr = "some resource";
        final byte[] fileContentBytes = fileContentsStr.getBytes();
        
  	final GeneralHelper generalHelper = context.mock(GeneralHelper.class);
  	context.checking(new Expectations() {
  	    {
  		exactly(1).of(generalHelper).getFileAsByteArray(with(any(File.class))); will(returnValue(fileContentBytes));
  	    }
  	});

  	ResourceResolver resourceResolver = new ResourceResolver(generalHelper)
  	{
  	    protected InputStream createInputStream(byte[] fileContents) {
  		return new ByteArrayInputStream(fileContentBytes);
  	    }

  	};
  	String type = "dont care";	
  	String namespaceURI = "also don't care";
  	String publicId = "used a bit";
  	String systemId = "xxxxhttp://xxx.com";	// The only thing we care about.
  	String baseURI = "again don't care";
  	LSInput resource = resourceResolver.resolveResource(type, namespaceURI, publicId, systemId, baseURI);
  	
  	String result = resource.getStringData();
  	assert result.equals(fileContentsStr);
  	
  	context.assertIsSatisfied();
    }

}
